package cn.eeepay.framework.service.unTransactionalImpl.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.eeepay.framework.dao.AgentAuthorizedDao;
import cn.eeepay.framework.dao.AgentAuthorizedOpenRecordMapper;
import cn.eeepay.framework.dao.TradeSumInfoMapper;
import cn.eeepay.framework.model.AgentAuthorizedOpenRecord;
import cn.eeepay.framework.model.TradeSumInfo;
import cn.eeepay.framework.model.three.AgentNameInfo;
import cn.eeepay.framework.model.three.SumDo;
import cn.eeepay.framework.model.three.TeamInfoEntry;
import cn.eeepay.framework.service.AgentInfoService;
import cn.eeepay.framework.service.SysDictService;
import cn.eeepay.framework.service.impl.TradeSumInfoService;
import cn.eeepay.framework.service.unTransactionalImpl.abstractJob.ScheduleJob;
import cn.eeepay.framework.util.DateUtil;

@Component
public class AgentAuthorizedOpenRecordJob extends ScheduleJob {

	@Autowired
	private AgentAuthorizedOpenRecordMapper agentAuthorizedOpenRecordMapper;
	@Autowired
	private AgentInfoService agentInfoService;
	@Autowired
	private TradeSumInfoService tradeSumInfoService;
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private TradeSumInfoMapper tradeSumInfoMapper;
	@Autowired
	private AgentAuthorizedDao agentAuthorizedDao;

	@Override
	public void runTask(String runNo) {
		// 超过多少天未激活 到期未激活专用
		String days = sysDictService.getByKey(TradeSumInfoService.EXPIRED_NOT_ACTIVATED_DAYS).getSysValue();
		// 拿到数据字典配置的所属组织
		String teamConfigStr = sysDictService.getValueByKey(TradeSumJob.THREE_INCOME_CALC_OEM);
		String[] teamArray = teamConfigStr.split("-");
		final List<String> teamList = new ArrayList<>();
		for (int i = 0; i < teamArray.length; i++) {
			teamList.add(teamArray[i]);
		}
		final List<String> teamEntryIdList = new ArrayList<>();

		// 有子组织的所属组织和没有子组织的所属组织分开计算
		for (Iterator<String> iterator = teamList.iterator(); iterator.hasNext();) {
			String teamId = (String) iterator.next();
			// 查询teamId下的子组织
			List<TeamInfoEntry> teamInfoEntryList = tradeSumInfoMapper.findTeamEntryByTeamId(teamId);
			if (teamInfoEntryList.size() > 0) {
				for (TeamInfoEntry teamInfoEntry : teamInfoEntryList) {
					teamEntryIdList.add(teamInfoEntry.getTeamEntryId());
				}
				iterator.remove();
			}
		}
		final boolean hasteamEntryId = teamEntryIdList.size() > 0;

		List<AgentAuthorizedOpenRecord> agentAuthorizedOpenRecordList = agentAuthorizedOpenRecordMapper.listAll();

		for (AgentAuthorizedOpenRecord agentAuthorizedOpenRecord : agentAuthorizedOpenRecordList) {
			String agentLink = agentAuthorizedOpenRecord.getAgentLink();
			String isTop = agentAuthorizedDao.getIsTopByAgentLink(agentLink);
			String agentAuthorized = agentAuthorizedOpenRecord.getAgentAuthorized();
			long countByAgentNo = tradeSumInfoMapper.countByAgenNo(agentAuthorized);
			if ("1".equals(isTop) && countByAgentNo < 1) {

				Date createDate = agentInfoService.selectByagentNo(agentAuthorized).getCreateDate();

				// 获取所有三方下级
				ArrayList<String> agentList = new ArrayList<>();
				agentList.add(agentAuthorized);
				tradeSumInfoService.getAllChildAgentNo(agentList, agentAuthorized);

				Date startDate = DateUtils.addDays(createDate, 1);
				Date endDate = new Date();
				// 两个时间区间对应的天数
				List<Date> timeList = getIntervalDateList(startDate, endDate, 1);

				// 三方报表
				for (Date date : timeList) {
					Date endTimeDate = DateUtils.addDays(date, -Integer.valueOf(days));
					this.threeCalcByTeamId(teamList, agentList, date, endTimeDate);
					// 子组织统计
					if (hasteamEntryId) {
						this.threeCalcByTeamEntryId(teamEntryIdList, agentList, date, endTimeDate);
					}
				}

			}

			Date createDate = agentInfoService.selectByagentNo(agentLink).getCreateDate();

			// 获取所有三方下级
			ArrayList<String> agentList = new ArrayList<>();
			agentList.add(agentLink);
			tradeSumInfoService.getAllChildAgentNo(agentList, agentLink);

			Date startDate = DateUtils.addDays(createDate, 1);
			Date endDate = new Date();
			// 两个时间区间对应的天数
			List<Date> timeList = getIntervalDateList(startDate, endDate, 1);

			// 三方报表
			for (Date date : timeList) {
				Date endTimeDate = DateUtils.addDays(date, -Integer.valueOf(days));
				this.threeCalcByTeamId(teamList, agentList, date, endTimeDate);
				// 子组织统计
				if (hasteamEntryId) {
					this.threeCalcByTeamEntryId(teamEntryIdList, agentList, date, endTimeDate);
				}
			}


			// 删除关联关系打开表数据
			agentAuthorizedOpenRecordMapper.deleteById(agentAuthorizedOpenRecord.getId());
		}

	}

	private void threeCalcByTeamId(List<String> teamList, List<String> list, Date date, Date endTimeDate) {
		Date yesterday = DateUtils.addDays(date, -1);
		String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", yesterday);
		String startTime = formatDate + " 00:00:00";
		String endTime = formatDate + " 23:59:59";
		if (list == null) {
			return;
		}
		List<String> sumAgentList = tradeSumInfoMapper.findSumAgentNo(startTime, endTime, list, teamList);
		List<String> agentList = new ArrayList<>();
		for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
			String agentNo = iterator.next();
			if (!sumAgentList.contains(agentNo)) {
				agentList.add(agentNo);
			}
		}
		if (agentList.size() < 1) {
			return;
		}

		List<SumDo> tradeSumList = tradeSumInfoMapper.tradeSumByList(agentList, startTime, endTime, teamList);
		List<SumDo> merSumList = tradeSumInfoMapper.merSumByList(agentList, startTime, endTime, teamList);
		List<SumDo> activateSumList = tradeSumInfoMapper.activateSumByList(agentList, startTime, endTime, teamList);
		List<SumDo> machinesStockList = tradeSumInfoMapper.machinesStockByList(agentList, startTime, endTime, teamList);
		List<SumDo> unusedMachinesList = tradeSumInfoMapper.unusedMachinesByList(agentList, startTime, endTime,
				teamList);
		List<SumDo> expiredNotActivatedList = tradeSumInfoMapper.expiredNotActivatedByList(agentList, endTimeDate);
		// 1-5级代理商名称信息
		List<AgentNameInfo> agentInfoList = tradeSumInfoMapper.findAgentInfoByNoList(agentList);
		// 顶层代理商名称信息
		List<AgentNameInfo> topAgentInfoList = tradeSumInfoMapper.findTopAgentInfoByNoList(agentList);

		for (String teamId : teamList) {
			for (String agentNoStr : agentList) {
				TradeSumInfo tradeSumInfo = new TradeSumInfo();
				tradeSumInfo.setCreateTime(yesterday);
				tradeSumInfo.setTeamId(teamId);
				for (SumDo sumDo : tradeSumList) {
					if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getTransAmount())) {
							tradeSumInfo.setTradeSum(new BigDecimal(sumDo.getTransAmount()));
							tradeSumInfo.setTradeCount(sumDo.getTradeCount());
						}
					}

				}
				if (tradeSumInfo.getTradeSum() == null) {
					tradeSumInfo.setTradeSum(BigDecimal.ZERO);
					tradeSumInfo.setTradeCount(0L);
				}
				for (SumDo sumDo : merSumList) {
					if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getMerSum())) {
							tradeSumInfo.setMerSum(Integer.valueOf(sumDo.getMerSum()));
						}
					}
				}
				if (tradeSumInfo.getMerSum() == null) {
					tradeSumInfo.setMerSum(0);
				}
				for (SumDo sumDo : activateSumList) {
					if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getActivateSum())) {
							tradeSumInfo.setActivateSum(Integer.valueOf(sumDo.getActivateSum()));
						}
					}
				}
				if (tradeSumInfo.getActivateSum() == null) {
					tradeSumInfo.setActivateSum(0);
				}
				for (SumDo sumDo : machinesStockList) {
					if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getMachinesStock())) {
							tradeSumInfo.setMachinesStock(Integer.valueOf(sumDo.getMachinesStock()));
						}
					}
				}
				if (tradeSumInfo.getMachinesStock() == null) {
					tradeSumInfo.setMachinesStock(0);
				}
				for (SumDo sumDo : unusedMachinesList) {
					if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getUnusedMachines())) {
							tradeSumInfo.setUnusedMachines(Integer.valueOf(sumDo.getUnusedMachines()));
						}
					}
				}
				if (tradeSumInfo.getUnusedMachines() == null) {
					tradeSumInfo.setUnusedMachines(0);
				}
				if ("100070".equals(teamId)) {
					for (SumDo sumDo : expiredNotActivatedList) {
						if (sumDo.getTeamId().equals(teamId) && sumDo.getAgentNo().equals(agentNoStr)) {
							if (StringUtils.hasLength(sumDo.getExpiredNotActivated())) {
								tradeSumInfo.setExpiredNotActivated(Integer.valueOf(sumDo.getExpiredNotActivated()));
							}
						}
					}
				} else {
					tradeSumInfo.setExpiredNotActivated(0);
				}
				if (tradeSumInfo.getExpiredNotActivated() == null) {
					tradeSumInfo.setExpiredNotActivated(0);
				}

				// 查询代理商名称
				for (AgentNameInfo info : agentInfoList) {
					if (info != null && info.getAgentNo().equals(agentNoStr)) {
						String agentName = info.getAgentName();
						Integer linkLevel = info.getLinkLevel();
						String agentInfo = agentName + "(" + agentNoStr + ")";
						switch (linkLevel) {
						case 1:
							tradeSumInfo.setOneLevel(agentInfo);
							break;
						case 2:
							tradeSumInfo.setTwoLevel(agentInfo);
							break;
						case 3:
							tradeSumInfo.setThreeLevel(agentInfo);
							break;
						case 4:
							tradeSumInfo.setFourLevel(agentInfo);
							break;
						default:
							tradeSumInfo.setFiveLevel(agentInfo);
							break;
						}
					}
				}
				if (tradeSumInfo.getOneLevel() == null && tradeSumInfo.getTwoLevel() == null
						&& tradeSumInfo.getThreeLevel() == null && tradeSumInfo.getFourLevel() == null
						&& tradeSumInfo.getFiveLevel() == null) {
					for (AgentNameInfo info : topAgentInfoList) {
						if (info != null && info.getAgentNo().equals(agentNoStr)) {
							String agentName = info.getAgentName();
							String agentInfo = agentName + "(" + agentNoStr + ")";
							tradeSumInfo.setBranch(agentInfo);
						}
					}
				}

				tradeSumInfo.setAgentNo(agentNoStr);
				tradeSumInfo.setUpdateTime(new Date());
				tradeSumInfo.setRecordedStatus(0);
				tradeSumInfo.setThreeIncome(BigDecimal.ZERO);
				tradeSumInfo.setIncomeCalc(0);
				// 保存
				tradeSumInfoMapper.insertSelective(tradeSumInfo);
			}
		}
	}
	
	private void threeCalcByTeamEntryId(List<String> teamEntryIdList, List<String> list, Date date, Date endTimeDate) {
		Date yesterday = DateUtils.addDays(date, -1);
		String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", yesterday);
		String startTime = formatDate + " 00:00:00";
		String endTime = formatDate + " 23:59:59";
		if (list == null) {
			return;
		}
		List<String> sumAgentList = tradeSumInfoMapper.findSumAgentNo(startTime, endTime, list, teamEntryIdList);
		List<String> agentList = new ArrayList<>();
		for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
			String agentNo = iterator.next();
			if (!sumAgentList.contains(agentNo)) {
				agentList.add(agentNo);
			}
		}
		if (agentList.size() < 1) {
			return;
		}
		List<SumDo> tradeSumList = tradeSumInfoMapper.tradeSumByListTeamEntry(agentList, startTime, endTime,
				teamEntryIdList);
		List<SumDo> merSumList = tradeSumInfoMapper.merSumByListTeamEntry(agentList, startTime, endTime,
				teamEntryIdList);
		List<SumDo> activateSumList = tradeSumInfoMapper.activateSumByListTeamEntry(agentList, startTime, endTime,
				teamEntryIdList);
		List<SumDo> machinesStockList = tradeSumInfoMapper.machinesStockByListTeamEntry(agentList, startTime, endTime,
				teamEntryIdList);
		List<SumDo> unusedMachinesList = tradeSumInfoMapper.unusedMachinesByListTeamEntry(agentList, startTime, endTime,
				teamEntryIdList);
		List<SumDo> expiredNotActivatedList = tradeSumInfoMapper.expiredNotActivatedByListTeamEntry(agentList,
				endTimeDate);
		// 1-5级代理商名称信息
		List<AgentNameInfo> agentInfoList = tradeSumInfoMapper.findAgentInfoByNoList(agentList);
		// 顶层代理商名称信息
		List<AgentNameInfo> topAgentInfoList = tradeSumInfoMapper.findTopAgentInfoByNoList(agentList);

		for (String teamEntryId : teamEntryIdList) {
			for (String agentNoStr : agentList) {
				TradeSumInfo tradeSumInfo = new TradeSumInfo();
				tradeSumInfo.setCreateTime(yesterday);
				tradeSumInfo.setTeamId(teamEntryId);
				for (SumDo sumDo : tradeSumList) {
					if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getTransAmount())) {
							tradeSumInfo.setTradeSum(new BigDecimal(sumDo.getTransAmount()));
							tradeSumInfo.setTradeCount(sumDo.getTradeCount());
						}
					}
				}
				if (tradeSumInfo.getTradeSum() == null) {
					tradeSumInfo.setTradeSum(BigDecimal.ZERO);
					tradeSumInfo.setTradeCount(0L);
				}
				for (SumDo sumDo : merSumList) {
					if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getMerSum())) {
							tradeSumInfo.setMerSum(Integer.valueOf(sumDo.getMerSum()));
						}
					}
				}
				if (tradeSumInfo.getMerSum() == null) {
					tradeSumInfo.setMerSum(0);
				}
				for (SumDo sumDo : activateSumList) {
					if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getActivateSum())) {
							tradeSumInfo.setActivateSum(Integer.valueOf(sumDo.getActivateSum()));
						}
					}
				}
				if (tradeSumInfo.getActivateSum() == null) {
					tradeSumInfo.setActivateSum(0);
				}
				for (SumDo sumDo : machinesStockList) {
					if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getMachinesStock())) {
							tradeSumInfo.setMachinesStock(Integer.valueOf(sumDo.getMachinesStock()));
						}
					}
				}
				if (tradeSumInfo.getMachinesStock() == null) {
					tradeSumInfo.setMachinesStock(0);
				}
				for (SumDo sumDo : unusedMachinesList) {
					if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
						if (StringUtils.hasLength(sumDo.getUnusedMachines())) {
							tradeSumInfo.setUnusedMachines(Integer.valueOf(sumDo.getUnusedMachines()));
						}
					}
				}
				if (tradeSumInfo.getUnusedMachines() == null) {
					tradeSumInfo.setUnusedMachines(0);
				}
				if (teamEntryId.contains("100070")) {
					for (SumDo sumDo : expiredNotActivatedList) {
						if (sumDo.getTeamId().equals(teamEntryId) && sumDo.getAgentNo().equals(agentNoStr)) {
							if (StringUtils.hasLength(sumDo.getExpiredNotActivated())) {
								tradeSumInfo.setExpiredNotActivated(Integer.valueOf(sumDo.getExpiredNotActivated()));
							}
						}
					}
				} else {
					tradeSumInfo.setExpiredNotActivated(0);
				}
				if (tradeSumInfo.getExpiredNotActivated() == null) {
					tradeSumInfo.setExpiredNotActivated(0);
				}

				// 查询代理商名称
				for (AgentNameInfo info : agentInfoList) {
					if (info != null && info.getAgentNo().equals(agentNoStr)) {
						String agentName = info.getAgentName();
						Integer linkLevel = info.getLinkLevel();
						String agentInfo = agentName + "(" + agentNoStr + ")";
						switch (linkLevel) {
						case 1:
							tradeSumInfo.setOneLevel(agentInfo);
							break;
						case 2:
							tradeSumInfo.setTwoLevel(agentInfo);
							break;
						case 3:
							tradeSumInfo.setThreeLevel(agentInfo);
							break;
						case 4:
							tradeSumInfo.setFourLevel(agentInfo);
							break;
						default:
							tradeSumInfo.setFiveLevel(agentInfo);
							break;
						}
					}
				}
				if (tradeSumInfo.getOneLevel() == null && tradeSumInfo.getTwoLevel() == null
						&& tradeSumInfo.getThreeLevel() == null && tradeSumInfo.getFourLevel() == null
						&& tradeSumInfo.getFiveLevel() == null) {
					for (AgentNameInfo info : topAgentInfoList) {
						if (info != null && info.getAgentNo().equals(agentNoStr)) {
							String agentName = info.getAgentName();
							String agentInfo = agentName + "(" + agentNoStr + ")";
							tradeSumInfo.setBranch(agentInfo);
						}
					}
				}

				tradeSumInfo.setAgentNo(agentNoStr);
				tradeSumInfo.setUpdateTime(new Date());
				tradeSumInfo.setRecordedStatus(0);
				tradeSumInfo.setThreeIncome(BigDecimal.ZERO);
				tradeSumInfo.setIncomeCalc(0);
				// 保存
				tradeSumInfoMapper.insertSelective(tradeSumInfo);
			}
		}
	}


	private List<Date> getIntervalDateList(Date startDate, Date endDate, int dateNum) {
		List<Date> list = new ArrayList<>();
		while (startDate.getTime() <= endDate.getTime()) {
			list.add(startDate);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startDate);
			// 开始时间加1
			calendar.add(Calendar.DAY_OF_YEAR, dateNum);
			if (calendar.getTime().getTime() > endDate.getTime()) {
				if (!startDate.equals(endDate)) {
					list.add(startDate);
				}
				startDate = calendar.getTime();
			} else {
				startDate = calendar.getTime();
			}
		}
		return list;
	}

}
